<?
/*
 *  GGB - Gelin's Guest Book.
 *  Copyright (C) 2006  Denis Nelubin aka Gelin
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *  http://gelin.ru
 *  mailto:den@gelin.ru
 *
 *  Description:    Base class for forms.
 *
 *  History:
 *  2006-08-05  Gelin   Initially created, methods moved from Formatter.php.
 *  2007-02-03  Gelin   Added handling of array request parameters.
 *  2007-02-03  Gelin   Now empty fields and absent fields are handled differently.
 *
 */

/**
 *  Base class for forms.
 */
class BaseForm {

    /**
     *  Prepares form field, defines it's name, value and maxlength.
     *  @param  $name   form field name
     *  @param  $value  form field value
     *  @return prepared field
     */
    function prepareFormField($name, $value) {
        global $config;
        $field['name'] = $name;
        $field['value'] = $value;
        $field['maxlength'] = $config['maxlength'][$name];
        return $field;
    }

    /**
     *  Get's form field from request, trim and truncate it.
     *  @param  $name   name of form field
     *  @return trimmed and truncated form field value or NULL of it's empty string
     */
    function getFormField($name) {
        $value = getParameter($name);
        if (isset($value)) {
            if (is_array($value)) {
                $newValue = array();
                foreach ($value as $key => $item) {
                    $item = $this->trimFormField($name, $item);
                    $newValue[$key] = $item;
                }
                $value = $newValue;
            } else {
                $value = $this->trimFormField($name, $value);
            }
        }
        return $value;
    }

    /**
     *  Trims form field according maxlength, defined in config.
     *  If maxlength is not defined, trim to 255 characters.
     *  @param  $name   name of a form field
     *  @param  $value  value of a field
     *  @return trummed value
     */
    function trimFormField($name, $value) {
        global $config;
        return substr((trim($value)), 0, ($config['maxlength'][$name] ? $config['maxlength'][$name] : 255));  //default maxlength = 255
    }

}

?>